package cn.sdack.go.users.controller;

import cn.sdack.go.common.entities.BaseEntity;
import cn.sdack.go.common.entities.JpaPage;
import cn.sdack.go.common.entities.JsonResult;
import cn.sdack.go.common.entities.users.AuthorityEntity;
import cn.sdack.go.common.entities.users.UserEntity;
import cn.sdack.go.common.querys.users.AuthorityQuery;
import cn.sdack.go.users.service.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author sdack
 * @date 2024/1/9
 */
@RestController
public class AuthorityController {

    @Autowired
    private AuthorityService authorityService;


    @PostMapping("/authority/page")
    public JsonResult query(@RequestParam(name = "page", defaultValue = "0") int page
            , @RequestParam(name = "pageSize", defaultValue = "0") int pageSize, @RequestBody AuthorityQuery param) {

        try {
            Page<AuthorityEntity> res = authorityService.queryAll(param, page, pageSize);
            return JsonResult.toJson(JpaPage.to(res));
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }


    @GetMapping("/authority/{id}")
    public JsonResult<?> getById(@PathVariable("id") Long id) {
        try {
            AuthorityEntity entity = authorityService.getById(id);
            return JsonResult.toJson(entity);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }


    @PostMapping("/authority")
    public JsonResult add(@RequestBody @Validated(BaseEntity.Add.class) AuthorityEntity param, BindingResult errors) {
        if (errors.hasErrors()) {
            return JsonResult.toJson(false, errors.getAllErrors().get(0).getDefaultMessage());
        }
        JwtAuthenticationToken authentication = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        String role = "";
        try {
            role = authentication.getToken().getClaim("role").toString();
        } catch (Exception e) {
            return JsonResult.toJson(false,"权限检查失败");
        }
        if (!UserEntity.Identity.SUPER.code.equals(role) && param.getGid() < 1) {
            return JsonResult.toJson(false,"组织必填");
        }
        try {
            AuthorityEntity res = authorityService.add(param);
            return JsonResult.toJson((res));
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }

    @PutMapping("/authority")
    public JsonResult set(@RequestBody @Validated(BaseEntity.Set.class) AuthorityEntity param, BindingResult errors) {
        if (errors.hasErrors()) {
            return JsonResult.toJson(false, errors.getAllErrors().get(0).getDefaultMessage());
        }
        try {
            authorityService.getById(param.getId());
            AuthorityEntity res = authorityService.set(param);
            return JsonResult.toJson((res));
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }

    @DeleteMapping("/authority/{id}")
    public JsonResult<?> del(@PathVariable("id") Long id) {
        try {
            authorityService.getById(id);
            authorityService.del(id);
            return JsonResult.toJson(true);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }


}
